<template>
    <div class="swiper">
        <ul :style="{
            width: banners.length*100 + '%',
            transition: transition,
            left: left
        }">
            <li :style="{
                width: 100 / banners.length + '%'
            }" @touchstart="touchStart" @touchmove="touchMove" @touchend="touchEnd" v-for="item in banners" :key="item.id">
                <img :src="item.picUrl" alt="">
            </li>
        </ul>
    </div>
</template>

<script>
var timer1, timer2
export default {
    name: '',
    props: {
        banners: Array,
        autoplay: {
            default: false
        }
    },
    data() { 
        return {
            dir: 'left',
            startX: 0,
            transition: 'none',
            left: '-100%'
        }
    },
    created() {
        if(this.autoplay !== false) {
            setInterval(() => {
                this.touchEnd()
            }, 3000);
        }
    },
    methods:{
        touchStart(e) {
            this.startX = e.touches[0].pageX
        },

        touchMove(e) {
            // console.log(e);
            let mX = e.touches[0].pageX
            if(mX - this.startX < 0) {
                this.dir = 'left'
            } else if(mX - this.startX > 0)  {
                this.dir = 'right'
            }
        },

        touchEnd() {
            clearInterval(timer1)
            clearInterval(timer2)
            this.transition = "all 0.5s linear"
            if(this.dir === 'left') {
                this.left = '-200%'
                timer1 = setTimeout(() => {
                    var item = this.banners.shift()
                    this.banners.push(item)
                    this.transition = 'none'
                    this.left = '-100%'
                }, 500)
            } else {
                this.left = '0%'
                timer2 = setTimeout(() => {
                    var item = this.banners.pop()
                    this.banners.unshift(item)
                    this.transition = 'none'
                    this.left = '-100%'
                }, 500)
            }
        }
    },
}
</script>

<style scoped lang="scss">
.swiper {
    width: 100%;
    height: auto;
    overflow: hidden;
    ul {
        display: flex;
        position: relative;
        left: 0;
        li {
            img {
                display: block;
                width: 100%;
                height: auto;
            }
        }
    }
}
</style>